from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import News, User, Comment
from info.moduls.news import news_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET
@news_blu.route('/news_comment',methods=['POST'])
@user_login_data
def comment_news():
    user=g.user
    if not user:
        return jsonify(errno=RET.NODATA,errmsg='您还没有登录')
    news_id=request.json.get("news_id")
    # print(news_id)
    comment_content=request.json.get("comment")
    # print(comment_content)
    parent_id=request.json.get("parent_id")
    if not all([news_id,comment_content]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
    try:
        news_id=int(news_id)
        if parent_id:
            parent_id=int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
    comment=Comment()
    comment.user_id=user.id
    comment.news_id=news_id
    comment.content=comment_content
    if parent_id:
        comment.parent_id=parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库操作错误')

    return jsonify(errno=RET.OK,data=comment.to_dict())


@news_blu.route('/news_collect',methods=['POST'])
@user_login_data
def collect_news():
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='您还没有登录')
    news_id=request.json.get("news_id")
    action=request.json.get("action")
    if not all([news_id,action]):
        return jsonify(error=RET.NODATA,errmsg='参数不全')
    if action not in("collect","cancel_collect"):
        return jsonify(errno=RET.DATAERR,errmsg='参数有误')
    try:
        news_id=int(news_id)
    except Exception as e:
        current_app.logger.error(e)
    news=None
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news :
        return jsonify(errno=RET.DATAERR,errmsg='传入新闻id有误')
    if action=="cancel_collect":
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            user.collection_news.append(news)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                current_app.logger.error(e)
    return jsonify(errno=RET.OK,errmsg='操作成功')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user
    comment=[]
    try:
        comment=Comment.query.filter(Comment.news_id==news_id).all()
    except Exception as e:
        current_app.logger.error(e)
    comment_li=[]
    for com in comment:
        comment_li.append(com.to_dict())
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)
    news.clicks+=1
    is_collected=True
    if user:
        # if news.id in [new.id for new in user.collection_news]:
        if news in user.collection_news:
            is_collected = False


    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for new in news_list:
        news_dict_list.append(new.to_basic_dict())

    data={
        "user": user.to_dict() if user else None,
        "news_dict_list": news_dict_list,
        "news":news.to_dict(),
        "is_collected":is_collected,
        "comments":comment_li
    }
    return render_template("news/detail.html",data=data)